const app = getApp();
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    nickName: null,
    picker: null,
    parent: false,
    teacher: false,
    typeArray: ['2', '1'], // 默认家长，2是家长，1是老师
    schoolId: null,
    schoolName: null,
    pickerIndex: 0,
    relationPicker: ['爸爸', '妈妈', '亲戚', '其他'],
    relationPickerIndex: null,
    firstTimeGetPhoneNumber: true, // 首次获取手机号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let openid = wx.getStorageSync('openid'); // 一般能进到这里已经有openid了
    let type = options.type;
    if (type == 0) {
      this.setData({
        picker: ['家长', '老师'],
        pickerIndex: 0,
        parent: false,
        teacher: false,
        openid
      })
    } else if (type == 1) {
      this.setData({
        picker: null,
        pickerIndex: 1,
        parent: false,
        teacher: true,
        openid
      })
    } else {
      this.setData({
        picker: null,
        parent: true,
        teacher: false,
        pickerIndex: 0,
        openid
      })
    }

    this.getSchoolInfo();
  },

  onHide: function () {
    this.setData({
      firstTimeGetPhoneNumber: true
    })
  },

  async getSchoolInfo() {
    let res = await requestUtil.request('GET', api.getSchoolList, null);
    //FIXME 因为只有一间学校，直接用数据了
    this.setData({
      schoolId: res.data.data[0].id,
      schoolName: res.data.data[0].schoolName
    })
  },

  pickerChange: function (e) {
    this.setData({
      pickerIndex: e.detail.value
    })
  },
  schoolPickerChange: function (e) {
    this.setData({
      schoolPickerIndex: e.detail.value
    })
  },
  relationPickerChange: function (e) {
    this.setData({
      relationPickerIndex: e.detail.value
    })
  },

  /**
   * 获取用户昵称
   */
  getNickName: function () {
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '用于完善资料',
      success: res => {
        let userInfo = res.userInfo;
        this.setData({
          nickName: userInfo.nickName
        })
      }
    })
  },

  /**
   * 表单确认
   */
  submitRegister(e) {
    let that = this;
    let formRes = e.detail.value;
    formRes.openid = this.data.openid;
    formRes.schoolId = this.data.schoolId;
    // 上传数据
    if (this.data.typeArray[this.data.pickerIndex] == 2 || this.data.parent) { // 家长则进入这里
      if (!formRes.studentName || formRes.studentName == '') {
        wx.showToast({
          title: '学生姓名不能为空',
          icon: 'none'
        })
        return false;
      } else if (!formRes.nickName || formRes.nickName == '') {
        wx.showToast({
          title: '昵称不能为空',
          icon: 'none'
        })
        return false;
      } else if (!formRes.phone || formRes.phone == '') {
        wx.showToast({
          title: '手机号码不能为空',
          icon: 'none'
        })
        return false;
      } else if (!formRes.relation || formRes.relation == '') {
        wx.showToast({
          title: '与学生关系不能为空',
          icon: 'none'
        })
        return false;
      } else {
        wx.request({
          url: api.baseUrl + '/user/bindStudent',
          header: {
            'content-type': 'application/json',
            'xcx-token': getApp().xcxtoken
          },
          method: 'POST',
          data: formRes,
          success: res => {
            if (res.data.code == '0') {
              app.globalData.isInitParent = true;
              app.globalData.userType = 2;
              that.getUserInfo(that.data.openid);
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'error'
              })
            }
          }
        })
      }
    } else if (this.data.typeArray[this.data.pickerIndex] == 1 || this.data.teacher) {
      // if (!formRes.name || formRes.name == '') {
      //   wx.showToast({
      //     title: '老师姓名不能为空',
      //     icon: 'none'
      //   })
      //   return false;
      // } 
      if (!formRes.mobile || formRes.mobile == '') {
        wx.showToast({
          title: '老师电话不能为空',
          icon: 'none'
        })
        return false;
      } else {
        wx.request({
          url: api.baseUrl + '/user/bindTeacher',
          header: {
            'content-type': 'application/json',
            'xcx-token': getApp().xcxtoken
          },
          method: 'post',
          data: formRes,
          success: res => {
            if (res.data.code == '0') {
              app.globalData.isInitTeacher = true;
              app.globalData.userType = 1;
              that.getUserInfo(that.data.openid);
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          }
        })
      }
    }
  },

  getUserInfo(id) {
    let that = this;
    wx.request({
      url: api.baseUrl + '/user/queryUserInfo',
      header: {
        'content-type': 'application/json',
        'xcx-token': getApp().xcxtoken
      },
      method: 'post',
      data: {
        openid: id
      },
      success: res => {
        if (res.data.code == 0) {
          app.globalData.teacherInfo = res.data.data.teacherInfo;
          app.globalData.parentInfo = res.data.data.parentInfo;
          that.swtichTabbar();
        }
      }
    })
  },

  swtichTabbar() {
    wx.switchTab({
      url: '/pages/index/index/index',
    })
  },

  async getPhoneNumber(e) {
    if (e.detail.errMsg.includes('user deny')) {
      wx.showToast({
        title: '请先使用手机号绑定身份',
        icon: 'none'
      })
    } else {
      let that = this;
      let params = {};
      let sessionKey = wx.getStorageSync('session_key')
      params.sessionkey = sessionKey;
      params.ivdata = e.detail.iv;
      params.encrypdata = e.detail.encryptedData;
      // 首次获取手机号
      if (this.data.firstTimeGetPhoneNumber) {
        wx.checkSession({
          //session_key 未过期，并且在本生命周期一直有效
          success: () => {
            that.getPhone(params);
          },
          // session_key 已经失效，需要重新执行登录流程
          fail: () => {
            wx.login({
              success: async function (res) {
                let init = await requestUtil.request("POST", api.initUser, {
                  code: res.code
                });
                wx.setStorage({
                  key: "session_key",
                  data: res.data.data.session_key
                });
                params.sessionkey = res.data.data.session_key;
                that.getPhone(params);
              }
            })
          }
        })
        that.setData({
          firstTimeGetPhoneNumber: false,
        })
      } else {
        wx.login({
          success: async function (res) {
            let init = await requestUtil.request("POST", api.initUser, {
              code: res.code
            });
            wx.setStorage({
              key: "session_key",
              data: init.data.data.session_key
            });
            params.sessionkey = init.data.data.session_key;
            that.getPhone(params);
          }
        })
      }
    }
  },

  async getPhone(params) {
    let res = await requestUtil.request("POST", api.getPhone, params);
    if (!res.data) {
      wx.showToast({
        title: '无法获取信息，请重试。',
        icon: 'none'
      })
    }
    let phone = res.data.purePhoneNumber; // 没有区号的手机号
    this.setData({
      phone: phone
    })
  }
})